package com.module.admin.rest.rmi.data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.stereotype.Component;

import com.system.cache.redis.BaseCache;
import com.system.comm.utils.FrameJsonUtil;
import com.system.rmi.model.RmiModel;
import com.system.rmi.service.DataCenterService;

/**
 * 服务端保存数据
 * @author yuejing
 *
 */
@Component
public class ServerDataCenterServiceImpl implements DataCenterService {

	private static BaseCache baseCache;
	private static final String RMI_SERVER_CACHE_KEY = "rmi_server_key";
	
	private String getRmiKey() {
		return RMI_SERVER_CACHE_KEY;
		
	}
	private BaseCache getBaseCache() {
		if(baseCache == null) {
			baseCache = new BaseCache();
			Map<String, String> map = getBaseCache().hgetAll(getRmiKey());
			if(map == null) {
				getBaseCache().hmset(getRmiKey(), new HashMap<String, String>());
			}
		}
		return baseCache;
	}

	@Override
	public void add(RmiModel rmiModel) {
		/*Map<String, RmiModel> data = getBaseCache().get(RMI_CACHE_KEY);
		if(data == null) {
			data = new HashMap<String, RmiModel>();
		}
		data.put(rmiModel.getUrl(), rmiModel);*/
		getBaseCache().hset(getRmiKey(), rmiModel.getUrl(), FrameJsonUtil.toString(rmiModel));
		/*List<String> urlList = getBaseCache().lrange(RMI_CACHE_KEY);
		if(!urlList.contains(rmiModel.getUrl())) {
			getBaseCache().lpush(RMI_CACHE_KEY, rmiModel.getUrl());
		}
		String rmiDtl = RMI_CACHE_KEY + rmiModel.getUrl();
		if(getBaseCache().get(rmiDtl) == null) {
			getBaseCache().set(rmiDtl, rmiModel);
		}*/
	}

	@Override
	public void del(String url) {
		//data.remove(url);
		/*getBaseCache().lrem(RMI_CACHE_KEY, url);
		getBaseCache().delete(RMI_CACHE_KEY + url);*/
		getBaseCache().hdel(getRmiKey(), url);
	}

	@Override
	public List<RmiModel> list() {
		/*List<RmiModel> list = new ArrayList<RmiModel>();
		List<String> urlList = getBaseCache().lrange(RMI_CACHE_KEY);
		for (String url : urlList) {
			RmiModel rmiModel = getBaseCache().get(RMI_CACHE_KEY + url);
			if(rmiModel != null) {
				list.add(rmiModel);
			}
		}
		return list;*/
		List<RmiModel> list = new ArrayList<RmiModel>();
		Map<String, String> map = getBaseCache().hgetAll(getRmiKey());
		if(map == null) {
			return list;
		}
		Iterator<Entry<String, String>> entryKeyIterator = map.entrySet().iterator();
		while (entryKeyIterator.hasNext()) {
			Entry<String, String> e = entryKeyIterator.next();
			String value = e.getValue();
			RmiModel rmiModel = FrameJsonUtil.toObject(value, RmiModel.class);
			list.add(rmiModel);
		}
		return list;
	}

}